<template>
  <div class="recommend-data-root">
    <!-- 筛选区 -->
    <el-form inline class="filter-bar">
      <el-date-picker 
        v-model="dateRange" 
        type="daterange" 
        range-separator="至" 
        start-placeholder="开始日期" 
        end-placeholder="结束日期" 
        style="margin-right: 16px;" 
      />
      <el-select 
        v-model="selectedScene" 
        placeholder="选择场景" 
        style="width: 140px; margin-right: 16px;"
        @change="handleSceneChange"
      >
        <el-option label="全部场景" value="" />
        <el-option label="首页" value="home" />
        <el-option label="分类页" value="category" />
        <el-option label="详情页" value="detail" />
        <el-option label="搜索页" value="search" />
      </el-select>
      <el-button @click="resetFilters">重置</el-button>
    </el-form>

    <!-- 核心指标卡片 -->
    <el-row :gutter="16" class="core-metrics">
      <el-col :span="4"><el-card>曝光量：{{ stats.views }}</el-card></el-col>
      <el-col :span="4"><el-card>点击量：{{ stats.clicks }}</el-card></el-col>
      <el-col :span="4"><el-card>点击率：{{ stats.ctr }}</el-card></el-col>
      <el-col :span="4"><el-card>转化量：{{ stats.conversions }}</el-card></el-col>
      <el-col :span="4"><el-card>转化率：{{ stats.cvr }}</el-card></el-col>
    </el-row>

    <!-- 趋势图表 -->
    <div class="trend-chart">
      <el-card>
        <v-chart :option="trendOption" autoresize style="height:320px;" />
      </el-card>
    </div>

    <!-- 商品排行榜 -->
    <el-card class="rank-table" style="margin-top: 24px;">
      <div slot="header">商品点击/转化排行榜</div>
      <el-table :data="productRank" border style="width: 100%">
        <el-table-column prop="name" label="商品" />
        <el-table-column prop="views" label="曝光" />
        <el-table-column prop="clicks" label="点击" />
        <el-table-column prop="ctr" label="点击率" />
        <el-table-column prop="conversions" label="转化" />
        <el-table-column prop="cvr" label="转化率" />
      </el-table>
    </el-card>

    <!-- 推荐位明细表 -->
    <el-card class="position-table" style="margin-top: 24px;">
      <div slot="header">推荐位明细</div>
      <el-table :data="positionStats" border style="width: 100%">
        <el-table-column prop="name" label="推荐位" />
        <el-table-column prop="views" label="曝光" />
        <el-table-column prop="clicks" label="点击" />
        <el-table-column prop="ctr" label="点击率" />
        <el-table-column prop="conversions" label="转化" />
        <el-table-column prop="cvr" label="转化率" />
      </el-table>
    </el-card>

    <!-- 用户分层转化漏斗 -->
    <el-card class="funnel-card" style="margin-top: 24px;">
      <div slot="header">用户分层转化漏斗</div>
      <el-tabs v-model="funnelTab" style="margin-bottom: 16px;">
        <el-tab-pane v-for="item in funnelTabs" :key="item.key" :label="item.label" :name="item.key" />
      </el-tabs>
      <v-chart :option="funnelOption" autoresize style="height:320px;" />
    </el-card>

    <!-- 推荐位多维对比 -->
    <el-card class="compare-card" style="margin-top: 24px;">
      <div slot="header">推荐位多维对比</div>
      <el-radio-group v-model="compareMetric" style="margin-bottom: 16px;">
        <el-radio-button v-for="item in compareMetrics" :key="item.key" :label="item.key">{{ item.label }}</el-radio-button>
      </el-radio-group>
      <v-chart :option="compareOption" autoresize style="height:320px;" />
    </el-card>

    <!-- 商品价格带分布 -->
    <el-card class="priceband-card" style="margin-top: 24px;">
      <div slot="header">商品价格带分布</div>
      <el-tabs v-model="priceBandTab" style="margin-bottom: 16px;">
        <el-tab-pane v-for="item in priceBandTabs" :key="item.key" :label="item.label" :name="item.key" />
      </el-tabs>
      <v-chart :option="priceBandOption" autoresize style="height:320px;" />
    </el-card>

    <!-- 高峰时段分析 -->
    <el-card class="hourtrend-card" style="margin-top: 24px;">
      <div slot="header">高峰时段分析</div>
      <v-chart :option="hourTrendOption" autoresize style="height:320px;" />
    </el-card>

    <!-- A/B测试结果对比 -->
    <el-card class="abtest-card" style="margin-top: 24px;">
      <div slot="header">A/B测试结果对比</div>
      <v-chart :option="abTestOption" autoresize style="height:320px;" />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { use } from 'echarts/core'
import VChart from 'vue-echarts'
import { PieChart, FunnelChart, LineChart, BarChart } from 'echarts/charts'
import { TitleComponent, TooltipComponent, LegendComponent, GridComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

use([PieChart, FunnelChart, LineChart, BarChart, TitleComponent, TooltipComponent, LegendComponent, GridComponent, CanvasRenderer])

const dateRange = ref([new Date('2024-06-01'), new Date('2024-06-07')])
const selectedPosition = ref('')
const selectedScene = ref('')

const recommendPositions = ref([
  { id: '1', name: '首页轮播', scene: 'home' },
  { id: '2', name: '分类页推荐', scene: 'category' },
  { id: '3', name: '详情页相关推荐', scene: 'detail' },
  { id: '4', name: '搜索页推荐', scene: 'search' }
])

// 根据场景筛选推荐位
const filteredPositions = computed(() => {
  if (!selectedScene.value) {
    return recommendPositions.value
  }
  return recommendPositions.value.filter(item => item.scene === selectedScene.value)
})

// 场景变化处理
const handleSceneChange = () => {
  selectedPosition.value = '' // 重置推荐位选择
  onSearch()
}

// 重置筛选条件
const resetFilters = () => {
  selectedScene.value = ''
  selectedPosition.value = ''
  dateRange.value = [new Date('2024-06-01'), new Date('2024-06-07')]
  onSearch()
}

const stats = ref({
  views: 10000,
  clicks: 1200,
  ctr: '12%',
  conversions: 300,
  cvr: '25%'
})

// mock趋势数据，支持多推荐位和场景
const trendData = ref([
  // 首页轮播
  { date: '2024-06-01', position: '1', scene: 'home', views: 1000, clicks: 120, conversions: 30 },
  { date: '2024-06-02', position: '1', scene: 'home', views: 1200, clicks: 150, conversions: 40 },
  { date: '2024-06-03', position: '1', scene: 'home', views: 1100, clicks: 130, conversions: 35 },
  { date: '2024-06-04', position: '1', scene: 'home', views: 1300, clicks: 160, conversions: 50 },
  { date: '2024-06-05', position: '1', scene: 'home', views: 1400, clicks: 170, conversions: 55 },
  { date: '2024-06-06', position: '1', scene: 'home', views: 1500, clicks: 180, conversions: 60 },
  { date: '2024-06-07', position: '1', scene: 'home', views: 1600, clicks: 200, conversions: 70 },
  // 分类页推荐
  { date: '2024-06-01', position: '2', scene: 'category', views: 800, clicks: 90, conversions: 20 },
  { date: '2024-06-02', position: '2', scene: 'category', views: 900, clicks: 100, conversions: 25 },
  { date: '2024-06-03', position: '2', scene: 'category', views: 950, clicks: 110, conversions: 28 },
  { date: '2024-06-04', position: '2', scene: 'category', views: 1000, clicks: 120, conversions: 30 },
  { date: '2024-06-05', position: '2', scene: 'category', views: 1100, clicks: 130, conversions: 35 },
  { date: '2024-06-06', position: '2', scene: 'category', views: 1200, clicks: 140, conversions: 38 },
  { date: '2024-06-07', position: '2', scene: 'category', views: 1300, clicks: 150, conversions: 40 },
  // 详情页相关推荐
  { date: '2024-06-01', position: '3', scene: 'detail', views: 600, clicks: 70, conversions: 15 },
  { date: '2024-06-02', position: '3', scene: 'detail', views: 700, clicks: 80, conversions: 18 },
  { date: '2024-06-03', position: '3', scene: 'detail', views: 750, clicks: 85, conversions: 20 },
  { date: '2024-06-04', position: '3', scene: 'detail', views: 800, clicks: 90, conversions: 22 },
  { date: '2024-06-05', position: '3', scene: 'detail', views: 850, clicks: 95, conversions: 24 },
  { date: '2024-06-06', position: '3', scene: 'detail', views: 900, clicks: 100, conversions: 26 },
  { date: '2024-06-07', position: '3', scene: 'detail', views: 950, clicks: 110, conversions: 28 },
  // 搜索页推荐
  { date: '2024-06-01', position: '4', scene: 'search', views: 500, clicks: 60, conversions: 10 },
  { date: '2024-06-02', position: '4', scene: 'search', views: 600, clicks: 70, conversions: 12 },
  { date: '2024-06-03', position: '4', scene: 'search', views: 650, clicks: 75, conversions: 14 },
  { date: '2024-06-04', position: '4', scene: 'search', views: 700, clicks: 80, conversions: 16 },
  { date: '2024-06-05', position: '4', scene: 'search', views: 750, clicks: 85, conversions: 18 },
  { date: '2024-06-06', position: '4', scene: 'search', views: 800, clicks: 90, conversions: 20 },
  { date: '2024-06-07', position: '4', scene: 'search', views: 850, clicks: 100, conversions: 22 },
])

// 过滤后的趋势数据
const filteredTrendData = ref<Array<{
  date: string
  views: number
  clicks: number
  conversions: number
}>>([])

function onSearch() {
  // 过滤日期
  const [start, end] = dateRange.value
  const filtered = trendData.value.filter(item => {
    const d = new Date(item.date)
    const inDate = (!start || d >= start) && (!end || d <= end)
    const matchPosition = !selectedPosition.value || item.position === selectedPosition.value
    const matchScene = !selectedScene.value || item.scene === selectedScene.value
    return inDate && matchPosition && matchScene
  })
  // 按日期聚合并排序
  const grouped: Record<string, typeof filtered[0][]> = {}
  filtered.forEach(item => {
    if (!grouped[item.date]) grouped[item.date] = []
    grouped[item.date].push(item)
  })
  filteredTrendData.value = Object.keys(grouped)
    .map(date => {
      const arr = grouped[date]
      return {
        date,
        views: arr.reduce((sum, i) => sum + i.views, 0),
        clicks: arr.reduce((sum, i) => sum + i.clicks, 0),
        conversions: arr.reduce((sum, i) => sum + i.conversions, 0)
      }
    })
    .sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime())
}

// 初始化默认筛选一次
onSearch()

const trendOption = computed(() => ({
  tooltip: { trigger: 'axis' },
  legend: { data: ['曝光量', '点击量', '转化量'] },
  xAxis: { type: 'category', data: filteredTrendData.value.map(i => i.date) },
  yAxis: { type: 'value' },
  series: [
    { name: '曝光量', type: 'line', data: filteredTrendData.value.map(i => i.views) },
    { name: '点击量', type: 'line', data: filteredTrendData.value.map(i => i.clicks) },
    { name: '转化量', type: 'line', data: filteredTrendData.value.map(i => i.conversions) }
  ]
}))

const productRank = ref([
  { name: 'iPhone 15 Pro', views: 2000, clicks: 300, ctr: '15%', conversions: 80, cvr: '26%' },
  { name: 'MacBook Pro 14', views: 1800, clicks: 250, ctr: '13.9%', conversions: 60, cvr: '24%' },
  { name: 'Nike Air Max', views: 1500, clicks: 200, ctr: '13.3%', conversions: 50, cvr: '25%' },
  { name: '小米13 Ultra', views: 1200, clicks: 150, ctr: '12.5%', conversions: 40, cvr: '26.7%' },
  { name: '华为 Mate 60 Pro', views: 1000, clicks: 120, ctr: '12%', conversions: 30, cvr: '25%' }
])

const positionStats = ref([
  { name: '首页轮播', views: 5000, clicks: 600, ctr: '12%', conversions: 150, cvr: '25%' },
  { name: '分类页推荐', views: 3000, clicks: 360, ctr: '12%', conversions: 90, cvr: '25%' },
  { name: '详情页相关推荐', views: 2000, clicks: 240, ctr: '12%', conversions: 60, cvr: '25%' },
  { name: '搜索页推荐', views: 1000, clicks: 120, ctr: '12%', conversions: 30, cvr: '25%' }
])

// 用户分层转化漏斗
const funnelTabs = [
  { label: '全部用户', key: 'all' },
  { label: '新用户', key: 'new' },
  { label: '老用户', key: 'old' },
  { label: 'VIP用户', key: 'vip' }
]
const funnelTab = ref('all')
const funnelDataMap: Record<string, { stage: string; value: number }[]> = {
  all: [
    { stage: '曝光', value: 12000 },
    { stage: '点击', value: 1800 },
    { stage: '加购', value: 700 },
    { stage: '下单', value: 350 },
    { stage: '支付', value: 220 }
  ],
  new: [
    { stage: '曝光', value: 4000 },
    { stage: '点击', value: 700 },
    { stage: '加购', value: 250 },
    { stage: '下单', value: 120 },
    { stage: '支付', value: 80 }
  ],
  old: [
    { stage: '曝光', value: 6000 },
    { stage: '点击', value: 800 },
    { stage: '加购', value: 300 },
    { stage: '下单', value: 160 },
    { stage: '支付', value: 100 }
  ],
  vip: [
    { stage: '曝光', value: 2000 },
    { stage: '点击', value: 300 },
    { stage: '加购', value: 150 },
    { stage: '下单', value: 70 },
    { stage: '支付', value: 40 }
  ]
}
const funnelOption = computed(() => ({
  tooltip: { trigger: 'item', formatter: '{b} : {c}' },
  series: [{
    type: 'funnel',
    left: '10%',
    width: '80%',
    data: funnelDataMap[funnelTab.value].map((i: { stage: string; value: number }) => ({ name: i.stage, value: i.value }))
  }]
}))

// 推荐位多维对比
const compareMetrics = [
  { label: '点击量', key: 'clicks' },
  { label: '点击率', key: 'ctr' },
  { label: '转化量', key: 'conversions' },
  { label: '转化率', key: 'cvr' },
  { label: '加购量', key: 'addCart' },
  { label: '收藏量', key: 'fav' }
]
const compareMetric = ref('clicks')
const compareData: Array<{ name: string; clicks: number; ctr: number; conversions: number; cvr: number; addCart: number; fav: number }> = [
  { name: '首页轮播', clicks: 900, ctr: 0.15, conversions: 220, cvr: 0.24, addCart: 120, fav: 60 },
  { name: '分类页推荐', clicks: 600, ctr: 0.13, conversions: 120, cvr: 0.20, addCart: 80, fav: 30 },
  { name: '详情页相关推荐', clicks: 400, ctr: 0.10, conversions: 60, cvr: 0.15, addCart: 40, fav: 15 },
  { name: '搜索页推荐', clicks: 200, ctr: 0.08, conversions: 30, cvr: 0.12, addCart: 20, fav: 8 }
]
const compareOption = computed(() => ({
  tooltip: { trigger: 'axis' },
  xAxis: { type: 'category', data: compareData.map(i => i.name) },
  yAxis: { type: 'value', axisLabel: compareMetric.value.endsWith('r') ? { formatter: (v: number) => (v * 100) + '%' } : undefined },
  series: [{
    name: compareMetrics.find(i => i.key === compareMetric.value)?.label,
    type: 'bar',
    data: compareData.map(i => i[compareMetric.value as keyof typeof i])
  }]
}))

// 商品价格带分布
const priceBandTabs = [
  { label: '全部', key: 'all' },
  { label: '首页轮播', key: '1' },
  { label: '分类页推荐', key: '2' }
]
const priceBandTab = ref('all')
const priceBandDataMap: Record<string, { band: string; value: number }[]> = {
  all: [
    { band: '0-199', value: 180 },
    { band: '200-499', value: 420 },
    { band: '500-999', value: 260 },
    { band: '1000+', value: 110 }
  ],
  '1': [
    { band: '0-199', value: 50 },
    { band: '200-499', value: 180 },
    { band: '500-999', value: 90 },
    { band: '1000+', value: 40 }
  ],
  '2': [
    { band: '0-199', value: 80 },
    { band: '200-499', value: 150 },
    { band: '500-999', value: 120 },
    { band: '1000+', value: 30 }
  ]
}
const priceBandOption = computed(() => ({
  tooltip: { trigger: 'item' },
  legend: { orient: 'vertical', left: 'left' },
  series: [{
    type: 'pie',
    radius: '60%',
    data: priceBandDataMap[priceBandTab.value].map((i: { band: string; value: number }) => ({ name: i.band, value: i.value }))
  }]
}))

// 高峰时段分析
const hourTrendData = [
  { hour: '00:00', views: 100 }, { hour: '01:00', views: 80 }, { hour: '02:00', views: 60 },
  { hour: '03:00', views: 50 }, { hour: '04:00', views: 40 }, { hour: '05:00', views: 30 },
  { hour: '06:00', views: 60 }, { hour: '07:00', views: 100 }, { hour: '08:00', views: 200 },
  { hour: '09:00', views: 400 }, { hour: '10:00', views: 600 }, { hour: '11:00', views: 800 },
  { hour: '12:00', views: 1000 }, { hour: '13:00', views: 900 }, { hour: '14:00', views: 800 },
  { hour: '15:00', views: 700 }, { hour: '16:00', views: 600 }, { hour: '17:00', views: 500 },
  { hour: '18:00', views: 700 }, { hour: '19:00', views: 900 }, { hour: '20:00', views: 1200 },
  { hour: '21:00', views: 1500 }, { hour: '22:00', views: 1800 }, { hour: '23:00', views: 200 }
]
const hourTrendOption = {
  tooltip: { trigger: 'axis' },
  xAxis: { type: 'category', data: hourTrendData.map(i => i.hour) },
  yAxis: { type: 'value' },
  series: [{ name: '曝光量', type: 'line', data: hourTrendData.map(i => i.views) }]
}

// A/B测试结果对比
const abTestData = [
  { group: 'A组', ctr: 0.13, cvr: 0.22 },
  { group: 'B组', ctr: 0.17, cvr: 0.28 }
]
const abTestOption = {
  tooltip: { trigger: 'axis' },
  legend: { data: ['点击率', '转化率'] },
  xAxis: { type: 'category', data: abTestData.map(i => i.group) },
  yAxis: { type: 'value', min: 0, max: 0.4, axisLabel: { formatter: (v: number) => (v * 100) + '%' } },
  series: [
    { name: '点击率', type: 'bar', data: abTestData.map(i => i.ctr) },
    { name: '转化率', type: 'bar', data: abTestData.map(i => i.cvr) }
  ]
}
</script>

<style scoped>
.recommend-data-root {
  padding: 24px;
  background: #f5f5f5;
  min-height: 100vh;
}
.filter-bar {
  margin-bottom: 24px;
}
.core-metrics {
  margin-bottom: 24px;
}
.trend-chart {
  margin-bottom: 24px;
}
.rank-table {
  margin-bottom: 24px;
}
.position-table {
  margin-bottom: 24px;
}
</style> 